<script setup lang="ts">
import {ref} from "vue";
import {useRouter} from "vue-router";

const searchText = ref('');

const originTagList = [
  {
    text: '游戏',
    children: [
      {text: 'LOL', id: 'LOL'},
      {text: '王者荣耀', id: '王者荣耀'},
    ],
  },
  {
    text: '技能',
    children: [
      {text: 'java', id: 'java'},
      {text: 'python', id: 'python'},
      {text: 'go', id: 'go'},
      {text: 'php', id: 'php'},
    ],
  }
];

let tagList = ref(originTagList);

/**
 * 此处的根据条件过滤不能修改源数组的值，否则会越过滤越小，
 * 比如下面的onSearch函数中没有对parentTag和children做任何处理，都是将原数组复制了一份再进行操作
 */
const onSearch = () => {
  tagList.value = originTagList.map(parentTag => {
    const tempParent = {...parentTag };
    const tempChildren = [...parentTag.children ];
    tempParent.children = tempChildren.filter(item=>item.text.includes(searchText.value));
    return tempParent;
  });
}

const onCancel = () => {
 searchText.value='';
 tagList.value=originTagList;
};


// 移除标签
const close = (tag) => {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag
  })
};

const activeIds = ref([]);
const activeIndex = ref(0);

// 根据搜索用户
const router = useRouter();
const doSearchUser = () => {
  router.push({
    path: '/user/search',
    query: {
      tags: activeIds.value
    }
  })
}

</script>

<template>
  <!--搜索框--->
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入要搜索的标签"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <!---分割线-->
  <van-divider content-position="left">已选择标签</van-divider>
  <div v-if="activeIds.length===0">请选择标签</div>
  <van-row gutter="12">
    <van-col v-for="tag in activeIds">
      <van-tag closeable style="" size="medium" type="primary" @close="close(tag)">
        {{ tag }}
      </van-tag>
    </van-col>
  </van-row>

  <van-divider content-position="left">请选择标签</van-divider>
  <!---供选择的标签-->
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />

  <div id="searchUserResult" style="padding: 12px">
    <van-button type="primary" block @click="doSearchUser()">用户搜索</van-button>
  </div>

</template>

<style scoped>

</style>